<template>
  <basic-container>
    <el-form
      ref="form"
      label-width="120px"
      style="display: flex; flex-wrap: wrap"
    >
      <el-form-item label="更新时间:">
        <el-date-picker
          size="mini"
          v-model="value1"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          ref="performTime" @visible-change="isShowSelectOptions" @change="submitForm">
        </el-date-picker>
      </el-form-item>
      <el-form-item tyle="width: 280px" label="媒体:">
        <el-select
          size="mini"
          v-model="form.platform"
          placeholder="请选择媒体"
          clearable
          ref="performPlatform" @visible-change="isShowSelectOptions" @change="submitForm">
          <el-option
            v-for="item in platformList"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="width: 280px">
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-search"
          @click="submitForm"
          >搜索</el-button
        >
        <el-button size="mini" icon="el-icon-delete" @click="resetSearch"
          >清空</el-button
        >
      </el-form-item>
    </el-form>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="tagData"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @sort-change="sortChange"
    >
      <template slot-scope="{ row }" slot="tags">
        <div><a href="javascript: void(0)" style="text-decoration: underline;" @click="onTagClick(row.tags)">{{ (row.tags == '')?'空':row.tags }}</a></div>
      </template>
      <template slot-scope="{ row }" slot="ctr">
        <div>{{ row.ctr }}%</div>
      </template>
      <template slot-scope="{ row }" slot="cvr">
        <div>{{ row.cvr }}%</div>
      </template>
    </avue-crud>

    <el-dialog
      title="预览"
      :visible="mediaPreviewDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :before-close="
        () => {
          mediaPreviewDialog.dialogVisible = false;
          if(mediaPreviewDialog.dialogType === 'video') {
            this.$refs.video.pause()
          }
        }
      "
      :append-to-body="true"
      style="text-align: center"
    >
      <img
        v-if="mediaPreviewDialog.dialogType === 'image'"
        :style="previewStyle()"
        :src="mediaPreviewDialog.previewUrl"
      />
      <video
        ref="video"
        v-if="mediaPreviewDialog.dialogType === 'video'"
        :src="mediaPreviewDialog.previewUrl"
        :style="previewStyle()"
        controls="controls"
      ></video>
    </el-dialog>

    <el-dialog
      :visible="creativePerformanceOnTagParams.visible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :append-to-body="true"
      style="text-align: center"
      :before-close="
        () => {
        creativePerformanceOnTagParams.visible = false;
        }
      "
    >
      <creative-performance-on-tag v-if="creativePerformanceOnTagParams.visible" :tags="creativePerformanceOnTagParams.tags" :params="creativePerformanceOnTagParams"></creative-performance-on-tag>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getTagList
} from "@/api/offer/creativeperformance";
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {getOutList} from '@/api/business/share'
import { getSysDictList } from "@/api/system/dict";
import { createEventHandler } from "@/util/events";
import { mapGetters } from "vuex";
import creativePerformanceOnTag from "./components/creativePerformanceOnTag";
import Moment from "moment";

export default {
  components: {
    creativePerformanceOnTag
  },
  data() {
    return {
      now: "",
      lastWeek: "",
      platformList: [],
      form: {
        platform: null,
        beginDate: null,
        endDate: null,
      },
      value1: [],
      query: {
        offerId: "",
        creativeId: "",
      },
      loading: true,
      selectionList: [],
      option: {
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: false,
        menu: false,
        addBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "标签",
            prop: "tags",
            slot: true,
          },
          {
            label: "关联素材数",
            prop: "creativeCount",
            sortable: 'custom',
          },
          {
            label: "总消耗",
            prop: "allExpend",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "曝光数",
            prop: "impressions",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            width:120,
            sortable: 'custom',
          },
          {
            label: "点击",
            prop: "clicks",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CTR",
            prop: "ctr",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            slot: true,
            sortable: 'custom',
          },
          {
            label: "安装",
            prop: "install",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CVR",
            prop: "cvr",
            rules: [
              {
                required: true,
                message: "请输入CVR",
                trigger: "blur",
              },
            ],
            slot: true,
            sortable: 'custom',
          },
        ],
      },
      tagData: [],
      sortList: [],
      mediaPreviewDialog: {
        dialogVisible: false,
        dialogType: "image", //image or video
        previewUrl: "",
      },
      isAdvSharedOffer: false,
      creativePerformanceOnTagParams: {
        visible: false,
        offer: '',
        tags: '',
        startDate: '',
        endDate: '',
      },
    };
  },
  computed: {
    ...mapGetters(["permission", "offer", "userInfo"]),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if (self.eventHandler) {
      self.eventHandler.clear();
    }
    next();
  },

  created() {
    //window.addEventListener('keyup', this.submitForm) //监听键盘事件
    this.lastWeek = Moment().subtract("months", 1).add("days",1).format("yyyy-MM-DD");
    this.now = Moment().format("yyyy-MM-DD");
    this.value1 = [this.lastWeek, this.now];

    let self = this;
    this.eventHandler = createEventHandler("offerCenter").addListener(
      (event) => {
        if (
          event.message == "offerChanged" &&
          event.offerId &&
          event.offerId !== ""
        ) {
          self.offer = event.offerId;
          self.refresh();
          self.onLoad(self.page, {});
          self.updateIsAdvSharedOffer();
        }
      }
    );

    this.refresh();
    if (this.$route.query.creativeId) {
      this.value1[0] = this.$route.query.beginDate;
      this.value1[1] = this.$route.query.endDate;
      this.onLoad(this.page, {});
    }
    self.updateIsAdvSharedOffer();
  },
  methods: {
    isShowSelectOptions(isShowSelectOptions){
      if(!isShowSelectOptions) this.$refs.performTime.blur();
      if(!isShowSelectOptions) this.$refs.performPlatform.blur();
    },
    previewStyle() {
      let height = window.innerHeight < 300 ? 300 : window.innerHeight - 160;
      return {
        maxWidth: "100%",
        maxHeight: height + "px",
      };
    },
    handleMediaPreview(row) {
      this.mediaPreviewDialog.previewUrl = row.creativeUrl + "?" + (row.updateTime ? row.updateTime.replace(/[ :-]*/gi, "") : 1234);
      this.mediaPreviewDialog.dialogType = row.type == 0 ? "image" : "video";
      this.mediaPreviewDialog.dialogVisible = true;
    },
    /**
     * 图片排序
     * @param val
     */
    sortChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if(orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.sortOnProp(prop, orderBy);
    },
    sortOnProp(prop, orderBy) {
      let sign = 0;
      if(orderBy == 'asc') {
        sign = 1;
      }
      if(orderBy == 'desc') {
        sign = -1;
      }
      this.tagData.sort((a,b)=>{return sign*(a[prop] - b[prop])});
    },
    setIsAdvSharedOfferChanged(val) {
      let self = this;
      self.isAdvSharedOffer = val;
    },
    updateIsAdvSharedOffer() {
      let self = this;
      if(self.userInfo.is_agency == 0) {
        self.loadOfferInfo(self.offer,(offerInfo)=>{
          if(offerInfo) {
            self.setIsAdvSharedOfferChanged(offerInfo.isShared == 1);
          } else {
            self.setIsAdvSharedOfferChanged(false);
          }
        });
      } else {
        self.setIsAdvSharedOfferChanged(false);
      }
    },
    loadOfferInfo(offerId,success) {
      if(offerId != null && offerId != '' && success) {
        getOfferDetail(offerId).then((res)=>{
          success(res.data.data);
        }).catch(()=>{
          success(null);
        });
      }
    },
    refresh() {
      //refresh开始，这样写避免代码迁移太多
      this.query.offerId = this.offer;
      getSysDictList("platforms").then((map) => {
        this.platformList = map['platforms']
      });
    },
    submitForm() {
      if (this.value1 != null) {
        this.form.beginDate = this.value1[0];
        this.form.endDate = this.value1[1];
      } else {
        this.form.beginDate = "";
        this.form.endDate = "";
      }
      this.onLoad(this.page, this.form);
    },
    resetSearch() {
      this.form = {
        platform: null,
        beginDate: "",
        endDate: "",
      };
      this.value1 = [];
      this.onLoad(this.page, this.form);
    },
    dialogType(val) {
      let type;
      let urlTail = val.split(".")[val.split(".").length - 1];
      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlTail)) {
        type = "image";
      } else if (videoList.includes(urlTail)) {
        type = "video";
      }
      return type;
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.value1 != null && this.value1.length == 2) {
        this.form.beginDate = this.value1[0];
        this.form.endDate = this.value1[1];
      } else {
        this.form.beginDate = "";
        this.form.endDate = "";
      }
      this.query.offerId = this.offer;
      getTagList(
        Object.assign({}, params, this.query, this.form, {sortList: JSON.stringify(this.sortList)})
      ).then((res) => {
        this.tagData = res.data.data;
        this.sortOnProp('allExpend', "desc");
        this.loading = false;
        this.selectionClear();
      });
    },
    onTagClick(tags) {
      this.$nextTick(() => {
        this.creativePerformanceOnTagParams.offer = this.offer;
        this.creativePerformanceOnTagParams.startDate = (this.value1 != null && this.value1.length == 2)?this.value1[0]:'';
        this.creativePerformanceOnTagParams.endDate = (this.value1 != null && this.value1.length == 2)?this.value1[1]:'';
        this.creativePerformanceOnTagParams.tags = tags;
        this.creativePerformanceOnTagParams.visible = true;
      });
    },
  },
};
</script>

<style>
</style>
